package com.mobilepay.moneypig.model.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.TipDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.NotesData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.LogDebug;
import com.mobilepay.moneypig.utils.acache.ACache;
import com.mobilepay.moneypig.view.DividerLine;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/7/26 0026
 */

public class NotesActivity extends BaseActivity {
    private static final String TAG = "NotesActivity";
    private RecyclerView mNotesRecycle;
    private SmartRefreshLayout smartRefreshLayout;
    private NotesAdapter mNotesAdapter;
    private static List<NotesData.DataBeanX.DataBean> mNoteList;
    private RelativeLayout mRelativeBack;

    private boolean isFirst = true;

    private int pagesize = 10;
    private int pagenum = 1;
    private int totalPage = -1;

    private static final int MODE_QUERY = 1;
    private static final int MODE_REFRESH = 2;
    private static final int MODE_MORE = 3;

    private static int CURRENT_MODE = MODE_QUERY;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_notes);
    }

    @Override
    protected void initViews() {
        mNotesRecycle = (RecyclerView) findViewById(R.id.notes_recycle);
        smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.notes_refresh);
        mRelativeBack = (RelativeLayout) findViewById(R.id.notes_back);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setmNotesAdapter();
        getNoteData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getNoteData();
    }

    @Override
    protected void onSetListener() {
        mRelativeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mNotesAdapter.setOnNoteClickListener(new NotesAdapter.OnNoteClickListener() {
            @Override
            public void onClick(int id, int uid) {
                Intent intent = new Intent();
                intent.putExtra("uid", uid);
                intent.putExtra("id", id);
                intent.setClass(getThis(), NoteDetailaActivity.class);
                startActivity(intent);
                LogDebug.d(TAG, "click");
            }
        });
        mNotesAdapter.setOnNoteLongClickListener(new NotesAdapter.OnNoteLongClickListener() {
            @Override
            public void onLongClick(int id, int uid) {
                showDeletDialog(id);
            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pagenum = 1;
                CURRENT_MODE = MODE_REFRESH;
                getNoteData();
            }
        });
        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
//                pagenum = mNoteList.size() / pagesize;
                if (totalPage != -1 && pagenum < totalPage) {
                    pagenum++;
                    CURRENT_MODE = MODE_MORE;
                    getNoteData();
                } else {
                    smartRefreshLayout.setEnableLoadmore(false);
                }
            }
        });
    }

    private TipDialog tipDialog;

    private void showDeletDialog(final int id) {
        if (tipDialog == null) {
            tipDialog = new TipDialog(this);
        }
        tipDialog.setCancelable(true);
        tipDialog.setContent("确认删除消息");
        tipDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                tipDialog.cancel();
                deleteNote(id);
            }

            @Override
            public void onDismiss() {
                tipDialog.cancel();
            }
        });
        tipDialog.show();
    }

    private void deleteNote(int id) {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.delete);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("id", String.valueOf(id));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 0) {
                        showToastShort(responseResult.getInfo());
                    } else {
                        showToastShort(responseResult.getInfo());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                getNoteData();
                            }
                        });
                    }
                }
            }
        });

    }

    private void getNoteData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.query);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("page_size", String.valueOf(pagesize));
        param.add("current_page", String.valueOf(pagenum));
        param.add("sign", param.getMd5String());
        showProgress("加载中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString(NetConfig.query);
                    if (!CommonUtil.isEmpty(jsonString)) {
                        mNoteList.clear();
                        setNotesData(jsonString, false);
                    }
                }
                if (totalPage != -1 && pagenum < totalPage) {
                    smartRefreshLayout.setEnableLoadmore(true);
                } else {
                    smartRefreshLayout.setEnableLoadmore(false);
                }
//                if (mNoteList.size() % pagesize == 0 && mNoteList.size() != 0) {
//                    smartRefreshLayout.setEnableLoadmore(true);
//                } else {
//                    smartRefreshLayout.setEnableLoadmore(false);
//                }
                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        smartRefreshLayout.finishRefresh(false);
                        break;
                    case MODE_MORE:
                        smartRefreshLayout.finishLoadmore(false);
                        break;
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        setNotesData(string, true);
                    } else {
                        showToastShort(responseResult.getInfo());
                        smartRefreshLayout.setEnableLoadmore(false);
                    }

                } else {
                    smartRefreshLayout.setEnableLoadmore(false);
                }
                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        smartRefreshLayout.finishRefresh(true);
                        break;
                    case MODE_MORE:
                        smartRefreshLayout.finishLoadmore(true);
                        break;
                }
                if (totalPage != -1 && pagenum < totalPage)

                {
                    smartRefreshLayout.setEnableLoadmore(true);
                } else

                {
                    smartRefreshLayout.setEnableLoadmore(false);
                }
//                if (mNoteList.size() % pagesize == 0 && mNoteList.size() != 0) {
//                    smartRefreshLayout.setEnableLoadmore(true);
//                } else {
//                    smartRefreshLayout.setEnableLoadmore(false);
//                }
            }
        });
    }

    private void setNotesData(String string, boolean save) {
        NotesData notesData = GsonUtil.GsonToBean(string, NotesData.class);
        totalPage = notesData.getData().getLast_page();
        List<NotesData.DataBeanX.DataBean> dataBeanList = notesData.getData().getData();
        if (CURRENT_MODE != MODE_MORE) {
            mNoteList.clear();
        }
        if (dataBeanList.size() != 0) {
            mNoteList.addAll(dataBeanList);
        } else {
            smartRefreshLayout.setEnableLoadmore(false);
        }
        if (save) {
            try {
                String json = GsonUtil.GsonString(mNoteList);
                JSONObject jsonObject = new JSONObject(string);
                JSONObject jsonObject1 = jsonObject.optJSONObject("data");
                JSONArray jsonArray = new JSONArray(json);
                jsonObject1.put("data", jsonArray);
                ACache.get(App.getApp()).put(NetConfig.query, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        mNotesAdapter.setNotesData(mNoteList);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mNotesAdapter.notifyDataSetChanged();
            }
        });
    }


    private void setmNotesAdapter() {
        mNoteList = new ArrayList<>();
        mNotesAdapter = new NotesAdapter(getThis());
        mNotesAdapter.setNotesData(mNoteList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getThis(), LinearLayoutManager.VERTICAL, false);
        DividerLine dividerLine = new DividerLine(DividerLine.VERTICAL);
        dividerLine.setSize(1);
        dividerLine.setColor(getResources().getColor(R.color.divider_line));
        mNotesRecycle.addItemDecoration(dividerLine);
        mNotesRecycle.setLayoutManager(layoutManager);
        mNotesRecycle.setAdapter(mNotesAdapter);
    }

    private static class NotesAdapter extends RecyclerView.Adapter<NotesViewHolder> {
        private Context context;
        private List<NotesData.DataBeanX.DataBean> beanList;
        private LayoutInflater inflater;

        public NotesAdapter(Context context) {
            this.context = context;
            this.inflater = LayoutInflater.from(context);
        }

        public void setNotesData(List<NotesData.DataBeanX.DataBean> dataBeanList) {
            this.beanList = dataBeanList;
        }

        @Override
        public NotesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new NotesViewHolder(inflater.inflate(R.layout.item_notes, parent, false));
        }

        @Override
        public void onBindViewHolder(NotesViewHolder holder, int position) {
            final NotesData.DataBeanX.DataBean bean = beanList.get(position);
            holder.mTextType.setText(bean.getTitle());
            holder.mTextContent.setText(bean.getBody());
            holder.mTextTime.setText(CommonUtil.formatDate(bean.getCreate_time() * 1000, "yyyy-M-d"));
            if (bean.getIs_look() == 0) {
                holder.imageView.setImageResource(R.mipmap.icon_note);
            } else {
                holder.imageView.setImageResource(R.mipmap.note_read);
            }
            //点击
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onNoteClickListener.onClick(bean.getId(), bean.getUid());
                }
            });
            //长按
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onNoteLongClickListener.onLongClick(bean.getId(), bean.getUid());
                    return true;
                }
            });

        }

        @Override
        public int getItemCount() {
            return beanList.size();
        }

        public void setOnNoteLongClickListener(OnNoteLongClickListener listener) {
            this.onNoteLongClickListener = listener;
        }

        public void setOnNoteClickListener(OnNoteClickListener listener) {
            this.onNoteClickListener = listener;
        }

        private OnNoteClickListener onNoteClickListener;
        private OnNoteLongClickListener onNoteLongClickListener;

        public interface OnNoteClickListener {
            void onClick(int id, int uid);
        }

        public interface OnNoteLongClickListener {
            void onLongClick(int id, int uid);
        }

    }

    static class NotesViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private TextView mTextType;
        private TextView mTextContent;
        private TextView mTextTime;
        private TextView mTextRed;

        public NotesViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.notes_image);
            mTextType = (TextView) itemView.findViewById(R.id.notes_type);
            mTextContent = (TextView) itemView.findViewById(R.id.notes_content);
            mTextTime = (TextView) itemView.findViewById(R.id.notes_time);
            mTextRed = (TextView) itemView.findViewById(R.id.notes_red);
        }
    }
}
